/**
 * Copyright (c) 2010 S9,Inc.All rights reserved.
 * Created by 2010-7-16 
 */
package cn.jdy.common.ctrl;

import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.jdy.framework.util.StringUtil;
import cn.jdy.plugins.entity.Member;
import cn.jdy.plugins.service.MemberService;

/**
 * 安全过滤器父类
 *
 * @author: zhaiguangtao
 * @data: 2013-7-1
 */
public class AuthcFilter implements Filter {
	public static String urls; //不需要权限过滤的url

	/**
	 * 参数初始化
	 */
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		
		/* 验证是否存在cookies 自动登录 */
		Object so = req.getSession().getAttribute("user");
		if(so == null) { // 查看cookies
			Cookie[] cookies = req.getCookies();
			if(cookies != null) {
				for(Cookie cookie : cookies) {
					if(cookie.getName().equalsIgnoreCase("authUser")) {
						try {
							String[] cookieValue = cookie.getValue().split("\\^");
							MemberService memberService = cn.jdy.framework.util.SpringContextUtils.getBean(MemberService.class);
							Member bo = memberService.findMemberByUsername(URLDecoder.decode(cookieValue[0],"UTF-8"));
							so = bo;
							if(cookieValue[1].equals(bo.getPassword())) {
								req.getSession().setAttribute("user", bo);
								req.getSession().setAttribute("isRemembered", true);//标识自动登录
							}
							break;
						} catch(Exception e) { }
					}
				}
			}
		}

		if(so == null) {
			String requestType = req.getHeader("X-Requested-With");
			if(StringUtil.isEmpty(requestType)) {
				// 替换 项目部署路径 ，只留项目相对根路径
				String uri = req.getRequestURI().replaceAll("^" + req.getContextPath(), "");

				// 获得请求中的参数
				String queryString = req.getQueryString();
				if(queryString == null) {
					queryString = "";
				}
				// 拼凑得到登陆之前的地址
				String realPath = uri + "?" + queryString;

			  /*  存放 Cookie */
				Cookie namecookie = new Cookie("prePage", realPath);
				//生命周期
				namecookie.setMaxAge(60 * 60 * 24);
				//设置哪个域名写cookie
				// namecookie.setDomain("http://127.0.0.1:8080");
				namecookie.setPath("/");
				res.addCookie(namecookie);
			}
		}
		chain.doFilter(request, response);
	}

	/**
	 * :系统关闭时的资源释放操作
	 */
	public void destroy() {

	}
}
